package org.budo.support.java.concurrent.thread.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lmw
 */
public class BudoThreadFactory implements ThreadFactory {
    private static final AtomicInteger _POOL_NUMBER = new AtomicInteger(1);

    private final ThreadGroup threadGroup;

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    private final String namePrefix;

    public BudoThreadFactory() {
        this("BudoThreadFactory.prefix");
    }

    public BudoThreadFactory(String prefix) {
        SecurityManager securityManager = System.getSecurityManager();
        threadGroup = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = prefix + "-pool-" + _POOL_NUMBER.getAndIncrement() + "-thread-";
    }

    public Thread newThread(Runnable runnable) {
        Thread thread = new Thread(threadGroup, //
                runnable, //
                namePrefix + threadNumber.getAndIncrement(), //
                0);

        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }

        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }

        return thread;
    }
}